import os,sys
import json
import numpy as np
import classification as cls

try:
    import classification as clf 
except ModuleNotFoundError:
    sys.path.insert(0,'/')
    sys.path.insert(0,os.path.split(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))[0])
    sub_path = os.path.abspath(__file__)
    sys.path.insert(0,os.path.split(sub_path)[0])
    import classification as clf
from sklearn import svm
from sklearn.svm import OneClassSVM, SVR

__version__ = '0.0.1'

def serialize_model(model):
    if isinstance(model,svm.SVC):
        return clf.serialize_svm(model)
    elif isinstance(model,OneClassSVM):
        return clf.serialize_oneclasssvm(model)
    else:
        raise ModelNotSupportError('this model type is not supported')

def deserialize_model(model_dict):
    if model_dict['meta'] == 'svm':
        return clf.deserialize_svm(model_dict)
    elif model_dict['meta'] == 'OneClassSVM':
        return clf.deserialize_oneclasssvm(model_dict)
    else:
        raise ModelNotSupportError('model type is not supported or corrupt JSON file')

def to_dict(model):
    return serialize_model(model)

def from_dict(model_dict):
    return deserialize_model(model_dict)

def to_json(model,model_name):
    with open(model_name,'w+') as model_json:
        json.dump(serialize_model(model),model_json)

def from_json(model_name):
    with open(model_name,'r') as model_json:
        model_dict = json.load(model_json)
        return deserialize_model(model_dict)

class ModelNotSupportError(Exception):
    """Exception raised for unsupported ML models."""
    
    def __init__(self, model_type, message=None):
        if message is None:
            message = f"Model type '{model_type}' is not supported."
        self.model_type = model_type
        super().__init__(message)
    
    def __str__(self):
        return f"{self.__class__.__name__}: {self.args[0]}"


if __name__ == '__main__':
    X = np.array([[1,1],[2,2],[3,3],[4,4],[5,5],[10,10],[11,11],[12,12]])
    oc_svm = OneClassSVM(nu=0.1,kernel='rbf',gamma=0.1)
    oc_svm.fit(X)
    to_json(oc_svm,'oc_svm.json')
    oc_svm_from_json = from_json('oc_svm.json')
    print(oc_svm_from_json) 